package com.bluetoothsms.common;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class MessageContacts extends BluetoothMessage {

	public MessageContacts(Contact[] c) {
		super(BtMessageType.Contacts, null);

		mData = new String[c.length * Contact.FIELD_COUNT];

		int i = 0;

		for (Contact contact : c) {
			mData[i++] = String.valueOf(contact.getId());
			mData[i++] = contact.getName();
			mData[i++] = Common.join(contact.getNumbers());
		}

	}

	public MessageContacts(byte[] data, int length) {
		super(BtMessageType.Contacts, data, length);
	}

	public Collection<Contact> getContacts() {
		List<Contact> list = null;

		if (mData.length % Contact.FIELD_COUNT == 0) {
			list = new ArrayList<Contact>(mData.length / Contact.FIELD_COUNT);
			String[] splits;

			for (int i = 0; i < mData.length; i += Contact.FIELD_COUNT) {
				splits = mData[i + 2].split(Common.DELIMITER);

				list.add(new Contact(Integer.valueOf(mData[i]), mData[i + 1],
						splits));
			}
		}

		return list;
	}
}
